package com.dst.smart.app;

import java.io.File;
import java.lang.reflect.Method;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Vector;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager.NameNotFoundException;
import android.media.AudioManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import com.dst.smart.R;
import com.dst.smart.constant.Constants;
import com.dst.smart.dialog.DownAlert;
import com.dst.smart.dialog.DownServiceAlert;
import com.dst.smart.json.BasicInfoUtils;
import com.dst.smart.model.BasicInfo;
import com.dst.smart.music.MusicPlayMedia;
import com.dst.smart.handler.SemanticResultHandler;
import com.dst.smart.json.MasterUtils;
import com.dst.smart.json.ProjectUtils;
import com.dst.smart.model.Master;
import com.dst.smart.model.ResultInfo;
import com.dst.smart.player.PlayController;
import com.dst.smart.player.TonePlayer;
import com.dst.smart.player.VolumeManager;
import com.dst.smart.receiver.ReceiverBroadcast;
import com.dst.smart.service.SendCMD;
import com.dst.smart.service.TcpSender;
import com.dst.smart.socket.ICoallBack;
import com.dst.smart.socket.ISocketPacket;
import com.dst.smart.socket.SocketClient;
import com.dst.smart.socket.info.ISocketCode;
import com.dst.smart.threadpool.ThreadPoolManager;
import com.dst.smart.threadpool.ThreadPoolTaskAiui;
import com.dst.smart.tools.AppTools;
import com.dst.smart.tools.CurrentVersion;
import com.dst.smart.tools.HPaConnector;
import com.dst.smart.tools.JSONHelper;
import com.dst.smart.tools.SystemInfo;
import com.dst.smart.utils.DevBoardControlUtil;
import com.dst.smart.utils.FileUtil;
import com.dst.smart.webservice.SettingServiceUtils;

import com.iflytek.aiui.AIUIErrorCode;
import com.iflytek.aiui.assist.player.AIUIPlayerKitVer;
import com.iflytek.aiui.assist.player.AIUIPlayer.ContentType;
import com.iflytek.aiui.assist.player.AIUIPlayer.PlayItem;
import com.iflytek.aiui.assist.player.AIUIPlayer.PlayState;
import com.iflytek.aiui.servicekit.AIUIAgent;
import com.iflytek.aiui.servicekit.AIUIConstant;
import com.iflytek.aiui.servicekit.AIUIEvent;
import com.iflytek.aiui.servicekit.AIUIListener;
import com.iflytek.aiui.servicekit.AIUIMessage;
import com.iflytek.aiui.servicekit.tts.InitListener;
import com.iflytek.aiui.servicekit.tts.SpeechSynthesizer;
import com.iflytek.aiui.assist.player.AIUIPlayer.AIUIPlayerListener;


public class MainActivity extends FragmentActivity {
	private final static String GRAMMAR_FILE_PATH = "grammar/grammar.bnf";
	// SerialPortAgent agent;
	// 唤醒角度
	private final static String KEY_ANGLE = "angle";
	private SemanticResultHandler mResultHandler;
	private PlayController mPlayController;
	// 網路連結
	// private static boolean isConect = false;
	// 主动休眠广播接收者
	private SleepBroadCastRecerver mSleepBroadCastRecerver;
	AudioManager mAudioManager;
	private static AIUIAgent mAIUIAgent;
	public static int isLinkFlag = 0;
	public static int plusNumber = 0;
	// 音量控制
	private VolumeManager mVolumeManager;

	// 文本合成以及音乐播放对象
	private static AIUIPlayerKitVer mAIUIPlayer;

	public static boolean musicIsSong = false;
    public static boolean musiconlyonce=false;

    public static int backCode = 0;

	// 是否在处理错误标记
	private boolean mIsHandlingError = false;
	public static int isPlayMusic = 0;
	// 判断是不是处于唤醒状态
	// public static boolean mIsWakeUp = false;
	public static int mIsWakeUp = 0;
	public static int mWeatherMode = 0;
	public static boolean mIsValidCmd = false;

	public static boolean mSoundTip = false;
	public static boolean DoNotDisturb = false;
	public static int playMode=0;
	private Vector<String> datas = new Vector<>();
	//public static List<SongPlayInfo> soundRecord = new ArrayList<>();
	// private Thread timmer = null;
	// 唤醒播放音频
	private final static String[] WAKE_UP_TONES = {
			Constants.XIAOAI_GREETING_EWZN,		// 嗯，我在呢
			Constants.XIAOAI_GREETING_GS,			// 干啥
			Constants.XIAOAI_GREETING_SS,			// 啥事
			Constants.XIAOAI_GREETING_WTZN 		// 我听着呢
	};
	// -------------------------------------------------------------
	protected static final String TAG = "AIUIDemo";
	public static boolean isForeground = false;
	private static Activity mContext;
	public static MainActivity activity;
	private View currentButton;
	public static boolean musicPlaySt = false;
	public static boolean musicTTsSt = false;
	//public static PlayItem recordSong;
	public static int isAirbus = 0;
	public ThreadPoolManager poolManager;
	private HomeFragment fragmentHome;
	public static String isUploadText = "";
	public static int isUploadIndex = 0;

	public static boolean isTTS = false;
	private static int prePriority = 0;
	// public static int preAlarmTime=0;
	public static int preAlarmNum = 0;
	public static String preAlarmStr = "";
	public static int sleepLight=0;

	// public static String certificatePath="";
	//public static int outsideTemp = 0;
	public static int insideTemp[] = {0,0,0,0,0,0,0,0};
	public static int Humidity[] = {0,0,0,0,0,0,0,0};
	public static int pm25[] = {0,0,0,0,0,0,0,0};
	public static int formaldehyde[]= {0,0,0,0,0,0,0,0};
	public static int illumination[] = {0,0,0,0,0,0,0,0};
	public static int NumberOfPeople=0;

	public static int addSensorTime=0;
	public static int addSensorId=0;
	//public static String AirQuality="";
	Runtime runtime;
	private static boolean inputKey = false;
	public SocketClient client;
	public void initSocket(){
		if (client == null) {

			client = new SocketClient(
					ProjectUtils.getRootPath().getServiceIP(), Constants._Port,
					2);

			client.setOnReceiveListener(new ISocketPacket() {
				@Override
				public void SocketPacket(String msg) {

					Intent intent = new Intent("com.dst.smart.receiver");
					Bundle bundle = new Bundle();
					bundle.putString("str", msg.trim());
					intent.putExtras(bundle);
					sendBroadcast(intent);

				}
			});
			// 设置连接服务器监听
			client.setOnConnectListener(new ICoallBack() {
				@Override
				public void OnSuccess(Socket client) {

					handler.sendEmptyMessage(0);
				}

				@Override
				public void OnDisConnect(String e) {
					// TODO Auto-generated method stub
					// initSocket();
					handler.sendEmptyMessage(1);
				}

				@Override
				public void OnLine() {
					// TODO Auto-generated method stub

				}

			});
		}
	}

	int count = 0;
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case -1:

				Master master = MasterUtils.getMaster(activity);

				String result = ISocketCode.setLine(master.getMn(),master.getPw());
				sendCode(result);

				break;
			case 0:
				Master masterL = MasterUtils.getMaster(activity);
				sendCode(ISocketCode.setLogin(masterL.getMn(), masterL.getPw()));
				break;
			case 2:

				break;
			case 3:
				break;
			case 4:
				break;
			case 5:
				break;
			case 6:
				byte[] b = { 3 };
				String hex = new String(b);
				String decode = msg.obj.toString();
				int cStartPos = decode.indexOf(hex);
				if ((cStartPos != -1)&&(decode.length()>2)) {
					if (decode.substring(0, 2).equals("*K")) {
						//mPlayController.onMusicCommand("", InsType.POOLTONE);
						if (preAlarmNum > 0) {
							preAlarmNum = 0;
							preAlarmStr = "";
							playSound(5, "清除所有通知");
						} else if (datas.size() > 0) {
							datas.clear();
						} else {
							// 短按
							int KeyIndex = Integer.valueOf(
									decode.substring(3, 4), 16);
							int LongTime = Integer.valueOf(
									decode.substring(4, 6), 16);
							if (decode.substring(2, 3).equals("S")) {
								switch (KeyIndex) {
								case 0:
								//	playSound(0, "你好我叫叮咚叮咚,我可以提供很多的服务喔");
									String resultStr= AppTools.wifiName();
									String cmd="你好我叫叮咚叮咚,";
									if(!resultStr.equals("")){
										cmd+="链接到网络:"+resultStr;
									}
									String hostIP = ProjectUtils.getRootPath()
											.getServiceIP();
									if (hostIP.equals("103.40.22.138")) {
										cmd+=",当前是:1号和利扬服务器";
									} else if (hostIP.equals("60.251.48.20")) {
										cmd+=",当前是:2号创力特服务器";
									}

									//MainActivity.playSound(5, cmd);
									PlayController.getInstance(activity).playURLList("", null);
									PlayController.getInstance(activity).playText("", cmd, true, 0, "", null);
									break;
								case 1:
									mVolumeManager.minusVolume();
									//if (MusicPlayMedia.getInstansMedia() != null) {
									//	MusicPlayMedia.setDownVolume();
									//}
									//exec("input keyevent " + KeyEvent.KEYCODE_VOLUME_DOWN );
									playSound(3, getString(R.string.lowVoice));
									break;
								case 2:
									//playSound(0, getString(R.string.key) + "2");
									break;
								case 3:
									String musicAction="";
									MainActivity.isPlayMusic=0;
									if (musicPlaySt) {
										musicAction=getString(R.string.stopPlay);
										if (MusicPlayMedia.getInstansMedia() != null) {
											MusicPlayMedia.getInstansMedia().pause();
										}
									}else{
										musicAction=getString(R.string.musicRlay);
										if (MusicPlayMedia.getInstansMedia() != null) {
											MusicPlayMedia.getInstansMedia().continuePlay();
										}
									}
									playSound(4,musicAction);
                                    break;
								case 4:
									//playSound(5, getString(R.string.key) + "4");
									break;
								case 5:
									mVolumeManager.plusVolume();
									//if (MusicPlayMedia.getInstansMedia() != null) {
									//	MusicPlayMedia.setUpVolume();
									//}
									//exec("input keyevent " + KeyEvent.KEYCODE_VOLUME_UP );
									playSound(3, getString(R.string.upVoice)); // playSound(getString(R.string.key)+"5");
									break;
								case 6:
									playSound(3, getString(R.string.lightClose));
									sleepLight=0;
									// playSound(getString(R.string.key)+"6");
									//if (mIsWakeUp > 0) {
									//	resetWakeup(false);
									//}
									//MainActivity.UploadText("停止播放",1);
									//exec("input keyevent " + KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE );
									break;
								}
							} else if (decode.substring(2, 3).equals("U")) {
								switch (KeyIndex) {
								case 0:
									break;
								case 1:
									if (musicPlaySt) {
										mVolumeManager.minusVolume();
										//if (MusicPlayMedia.getInstansMedia() != null) {
										//	MusicPlayMedia.setDownVolume();
										//}
										playSound(3, getString(R.string.lowVoice));
									}else {
										playSound(3, getString(R.string.lowLeave));
									}
									break;
								case 2:
									playSound(3, getString(R.string.changeMode));
									break;
								case 3:
									String musicAction = "";
									MainActivity.isPlayMusic=0;
									if (musicPlaySt) {
										musicAction = getString(R.string.stopPlay);
										if (MusicPlayMedia.getInstansMedia() != null) {
											MusicPlayMedia.getInstansMedia().pause();
										}
									} else {
										musicAction = getString(R.string.musicRlay);
										if (MusicPlayMedia.getInstansMedia() != null) {
											MusicPlayMedia.getInstansMedia().continuePlay();
										}
									}
									playSound(5, musicAction);
									break;
								case 4:
									playSound(3, getString(R.string.changeMode));
									break;
								case 5:
									if (musicPlaySt) {
										mVolumeManager.plusVolume();
										//if (MusicPlayMedia.getInstansMedia() != null) {
										//	MusicPlayMedia.setUpVolume();
										//}
										playSound(3, getString(R.string.upVoice)); // playSound(getString(R.string.key)+"5");
									}else{
										playSound(3, getString(R.string.upLeave));
									}
									break;
								case 6:
									playSound(3, getString(R.string.lightOpen));
									final Random random = new Random();
									sleepLight=random.nextInt(7) + 1;
									//MainActivity.UploadText("播放劉德華的歌",1);
									break;
								}
							}
							// 長按
							else if (decode.substring(2, 3).equals("L")) {
								if (LongTime == 96) {
									switch (KeyIndex) {
									case 0:
										break;
									case 1:
										break;
									case 2:
										break;
									case 3:
										break;
									case 4:
										break;
									case 5:
										break;
									case 6:
										break;
									case 7:
										break;
									}
								} else {
									switch (KeyIndex) {
									case 0:
									case 6:
										PlayController.getInstance(activity).playURLList("", null);
										PlayController.getInstance(activity).playText("","开始连接网络");
										ReceiverBroadcast.isNet=0;
									//	HPaConnector.getInstance(activity).removeAp(SystemInfo.getSSID(activity));
                                        break;
									case 1:
										break;
									case 2:
										break;
									case 3:
										break;
									case 4:
										break;
									case 5:
										break;
									case 7:
										playSound(5,getString(R.string.Restorefactory));
										// 恢复出厂设置\
										MasterUtils.reset();
										HPaConnector.getInstance(activity).removeAp(SystemInfo.getSSID(activity));
										break;
									}
								}
							} else if (decode.substring(2, 3).equals("E")) {
								switch (KeyIndex) {
								case 0: // 1527 windows配對訊息
									/*
									 * if (LongTime == 0) { playSound(5,
									 * "窗帘电机進行学习!"); } else if (LongTime == 1) {
									 * playSound(5, "奧科遙控器学习成功!"); } else if
									 * (LongTime == 2) { playSound(5,
									 * "杜亞遙控器学习成功!"); } else if (LongTime == 3)
									 * { playSound(5, "窗帘电机配对删除!"); }
									 */
									break;
								case 1: //
									if (LongTime == 0) {
										playSound(5, "安防進行配対学习!");
									} else if (LongTime == 1) {
										playSound(5, "安防配対成功!");
									} else if (LongTime == 2) {
										playSound(5, "安防配対超時!");
									}
									break;
								case 2: //
									break;
								}
							}
						}
					} else {
						// ss
						if (decode.indexOf("DST NETWORK") != -1) {
							if (!TcpSender.deviceID.equals("")) {
								sendCode(ISocketCode.setResponse(
										decode.substring(0, cStartPos),
										TcpSender.deviceID));
								TcpSender.deviceID = "";
							}
						} else {
							if(decode.startsWith("*")) {

								Log.e("cmdCode",decode);
								if(decode.startsWith("*C")){
									if(decode.length()>26){
										sendCode(ISocketCode.setResponse(decode.substring(0, 24), "000"));
									}else {
										sendCode(ISocketCode.setResponse(decode.substring(0, cStartPos), "000"));
									}
								}else{
									String cmd = decode.substring(0, cStartPos);
									sendCode(ISocketCode.setResponse(cmd, "000"));
								}

//								Log.e("cmdCode",cmd);
								//篩選來自串口的指令傳送至其他网關
//								String s = cmd.substring(0, 2);
//								Boolean IsSendFlag = false;
//								if (s.equals("*C")) {
//									s = cmd.substring(4, 6);
//									String tempType = cmd.substring(8, 10);
//									if (((s.equals("09") || s.equals("19")) && !tempType.equals("07"))
//											|| s.equals("32") || s.equals("0A")) {
//										IsSendFlag = true;
//									}
//								}
//								if (IsSendFlag) {
//									List<GateWay> gateWayList = GateWayFactory.getAll();
//									for (int i = 0; i < gateWayList.size(); i++) {
//										GateWay gateway = gateWayList.get(i);
//										int gatewayTypeID = gateway.getTypeId();
//										if (gateway.getSeqencing() ==1) { //joe
//											if ((gatewayTypeID == 4) || (gatewayTypeID == 5)) {
//												try{
//													Thread.sleep(50);
//												} catch (Exception e) {
//													e.printStackTrace();
//												}
//												String deviceID = gateway.getGatewayID();
//												MainActivity.activity.sendCode(ISocketCode.setForward(cmd,
//														deviceID));
//											}
//										}
//									}
//								}
								if (backCode > 0) {
									if ("*C".equals(decode.substring(0, 2))) {
										// 標準指令
										playSound(5, "监测无线数据成功");
										backCode--;
									}
								}
							}
						}
						TcpSender.dataProcess(decode);
					}
				}
				break;
			case 7:
				break;
			case 8:
				break;
			case 9:
				if (MusicPlayMedia.getInstansMedia() != null) {
					MusicPlayMedia.getInstansMedia().pause();
				}
				break;
			case 10:
				if (MusicPlayMedia.getInstansMedia() != null) {
					MusicPlayMedia.getInstansMedia().continuePlay();
				}
				break;
			case 11:
				try {
					JSONObject object = new JSONObject(msg.obj.toString());
					int musicType = object.getInt("musicType");
					String musicUrl = object.getString("musicUrl");
					String musicName = object.getString("musicName");
					playMusic(musicType,musicUrl);
					playSound(5, musicName);

				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case 12:
				// ScheduleUtil.getList(AppTools.getCurrentlyDate());
				break;
			default:
				break;
			}
		};
	};

	public void sendCode(String cmd) {
		try {
			 client.SenddData(cmd);


		} catch (Exception e) {
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mContext = this;
		activity = this;
		MasterUtils.getMaster(activity);
		mPlayController = PlayController.getInstance(mContext);
		mPlayController.setMaxVolum();

		poolManager = new ThreadPoolManager(0, 20);
		poolManager.start();

		mAudioManager = (AudioManager) getSystemService(activity.AUDIO_SERVICE);
		initAIUI();
		//resetWakeup(false);	//joe 2017 12 17 off
		fragmentHome = (HomeFragment) this.getSupportFragmentManager()
				.findFragmentById(R.id.homeFragment);



		BasicInfo basicInfo=BasicInfoUtils.getBasic(activity);
		if(basicInfo!=null){
			MusicPlayMedia.getInstansMedia().setVolume(Integer.parseInt(basicInfo.getVol()));
			mVolumeManager.setVolume(Integer.parseInt(basicInfo.getVol()));
			playSound(5, basicInfo.getGreetingInfo());
		}
		initSocket();
	}

	public void setVolum(int volume) {
		// if (mAudioManager != null) {
		// mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volun,
		// volun);
		// }
		mVolumeManager.setVolume(volume);
	}

	@Override
	protected void onPause() {
		isForeground = false;
		super.onPause();
	}

	@SuppressWarnings("unused")
	private void setButton(View v) {
		if (currentButton != null && currentButton.getId() != v.getId()) {
			currentButton.setEnabled(true);
		}
		v.setEnabled(false);
		currentButton = v;
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {// TODO
		// if (keyCode == KeyEvent.KEYCODE_BACK) {
		unregisterReceiver(mSleepBroadCastRecerver);

		this.finish();
		// return true;
		// }
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub

		switch (item.getItemId()) {

		case android.R.id.home:
			// DST20160608090806
			playSound(3, getString(R.string.key) + "0");
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onMenuOpened(int featureId, Menu menu) {
		if (featureId == Window.FEATURE_ACTION_BAR && menu != null) {
			if (menu.getClass().getSimpleName().equals("MenuBuilder")) {
				try {
					Method m = menu.getClass().getDeclaredMethod(
							"setOptionalIconsVisible", Boolean.TYPE);
					m.setAccessible(true);
					m.invoke(menu, true);

				} catch (Exception e) {
				}
			}
		}
		return super.onMenuOpened(featureId, menu);
	}

	// private JSONObject jsonObject;

	public static int curpos = 0;
	public static String curTitle = "";

	@Override
	protected void onDestroy() {
		super.onDestroy();

	}

	public void initAIUI() {
		SpeechSynthesizer synthesizer = SpeechSynthesizer.createSynthesizer(
				activity, new InitListener() {

					@Override
					public void onInit(int arg0) {
						// TODO Auto-generated method stub

					}
				});
		// 创建播放器，用于播放音乐和语音合成
		mAIUIPlayer = new AIUIPlayerKitVer(activity, synthesizer);

		AIUIListener aiuiListener = new AIUIListener() {

			@Override
			public void onEvent(AIUIEvent event) {
				// TODO Auto-generated method stub

				long posRsltOnArrival = System.currentTimeMillis();
				switch (event.eventType) {
				case AIUIConstant.EVENT_BIND_SUCCESS:
					buildGrammar();
					break;
				case AIUIConstant.EVENT_WAKEUP:

					try {
						// 获得唤醒角度
						JSONObject wakeInfo = new JSONObject(event.info);
						int wakeAngle = wakeInfo.getInt(KEY_ANGLE);
						DevBoardControlUtil.wakeUpLight(wakeAngle);
						HomeFragment.setCode("" + wakeInfo.getInt("power"));
						if (wakeInfo.getInt("power") != -1) {
							datas.clear();
							BasicInfo basicInfo=BasicInfoUtils.getBasic(activity);
							if(basicInfo!=null&&!basicInfo.getWakeUpWord().equals("no")){
								mPlayController.playText("",basicInfo.getWakeUpWord());
							}else{
								final Random random = new Random();
								mPlayController.playTone("",WAKE_UP_TONES[random.nextInt(4)]);
							}
							MusicPlayMedia.getInstansMedia().setVol(false);
							mIsWakeUp = 255;
							mWeatherMode=0;
							mIsValidCmd = true;
							if (null != mAIUIPlayer) {
								mAIUIPlayer.stop();
							}
						}
						mIsHandlingError = false;

					} catch (JSONException e) {
						e.printStackTrace();
					}
					break;
				case AIUIConstant.EVENT_SLEEP: {
					// 只处理因交互超时触发的自动休眠

					if (AIUIConstant.TYPE_AUTO == event.arg1) {
						datas.clear();
						if (null == mAIUIPlayer) {
							return;
						}
						if (null != mAIUIPlayer) {
							mAIUIPlayer.stop();
						}
						// joe 2017/03/07 正在播放音樂靜音休眠
						//if ((mAIUIPlayer.getPlayState() == PlayState.MUSIC_PLAYING)
						//		|| musicPlaySt||musicTTsSt) {
						//	// DevBoardControlUtil.closeDirectionLight();
						//	resetWakeup(false);
						//	// mIsWakeUp = false;
						//} else {
							// 自动休眠
							playGoodByeTheSleep("", false);
						//}
						mIsValidCmd = false;
					}
				}
					break;
				case AIUIConstant.EVENT_RESULT:
					if (mIsWakeUp == 0) {
						return;
					}
					try {
						MyApplication.getInstance().isDown = 0;
						Log.e("save",event.info);
						JSONObject bitParamJson = new JSONObject(event.info);
						JSONObject data = bitParamJson.getJSONArray("data")
								.getJSONObject(0);
						JSONObject params = data.getJSONObject("params");
						JSONObject content = data.getJSONArray("content")
								.getJSONObject(0);
						if (content.has("cnt_id")) {
							String cnt_id = content.getString("cnt_id");
							JSONObject cntJson = new JSONObject(new String(
									event.data.getByteArray(cnt_id), "utf-8"));
							String sub = params.getString("sub");
							if ("nlp".equals(sub)) {
								if ((isAirbus == 0) || !isUploadText.equals("")) { // 有Airbus設備
									String resultStr = cntJson
											.optString("intent");
									// sendMsg(resultStr);
									if ((!resultStr.equals("{}"))
											&& (!resultStr.equals(""))) {
										//isAirbus=60;	//消除語音連續尾音,如連說兩次
										long posRsltParseFinish = System.currentTimeMillis();
										JSONObject jsonObject=	new JSONObject(resultStr);
										mResultHandler.handleResult(jsonObject, event.data, params.toString(), posRsltOnArrival, posRsltParseFinish);
									}
								}
							} else if ("asr".equals(sub)) {
								// 处理离线语法结果
								String resultStr = cntJson.optString("intent");
								JSONObject resultJson = new JSONObject(
										resultStr);
								if (null != resultJson) {
									try {
										if (resultJson.getInt("rc") != 4) {
											JSONObject ws = (JSONObject) resultJson
													.getJSONArray("ws").get(0);
											JSONObject cw = (JSONObject) ws
													.getJSONArray("cw").get(0);
											// id =
											// Integer.valueOf(cw.getString("id"));
											final String result = cw
													.getString("w");
											HomeFragment
													.setCode("remenberNameAsr:"
															+ result);
											switch (Integer.valueOf(cw
													.getString("id"))) {
											case 2001:
												if (null == mAIUIPlayer) {
													return;
												}
												// joe 2017/03/07 正在播放音樂靜音休眠
												if ((mAIUIPlayer.getPlayState() == PlayState.MUSIC_PLAYING)
														|| musicPlaySt||musicTTsSt) {
													// DevBoardControlUtil.closeDirectionLight();
													resetWakeup(false);
													// mIsWakeUp = false;
												} else {
													// 自动休眠
													playGoodByeTheSleep("",
															false);
												}
												break;
											default:
												// isAirbus = 0;
												// if (mIsValidCmd) {
												// playSound(result);
												SendCMD cmdsend = SendCMD.getInstance();
												//cmdsend.sendCMD(0, result, null);
												cmdsend.sendSubCmd(0, result, null,0);
												if (isAirbus > 0) {
													mPlayController.playTone("",Constants.SEARCH_RESULT);
													// mIsValidCmd=false;
												}
												mIsValidCmd = false;
												// }
												break;
											}
										} else {
											// 空結果
										}
									} catch (JSONException e) {
										e.printStackTrace();
										// id = 0;
									}
								}
							} else if ("iat".equals(sub)) {
								// joe
								if (mIsWakeUp < 255) {
									return;
								}
								String resultStr = new String(
										event.data.getByteArray(cnt_id),
										"utf-8");
								final String result = parseIatResult(resultStr)
										.trim();
								if (!result.equals("") && !result.equals("。")
										&& (result.length() > 1)) {
									musicIsSong = false;
									//HomeFragment.setCode("remenberName:" + result);
									Log.e("text","iat "+result);
									if (mIsValidCmd
											|| (ProjectUtils.getRootPath()
													.getInteractive() > 0)) {
										// joe add 2017_1026
										//CheckMusic(result);
									 	if (isAirbus == 0) {
											SendCMD cmdsend = SendCMD.getInstance();
											//cmdsend.sendCMD(0, result, null);
											cmdsend.sendSubCmd(0, result, null,0);
											// playSound(result);

											HomeFragment.setCode("remenberName" + result);
											String postServer="aiuiE"; //Air Bus 未做任何事
											if (isAirbus > 0) {
												//Air Bus 成功
												if(mIsWakeUp>0) {
													TonePlayer.playTone(mContext,Constants.SEARCH_RESULT);
												}
												// mIsValidCmd=false;
												postServer="aiuiS";
											}
											String[] ackData = {"你好", "服务员", "服务生","前台","总台"};
											for (String str: ackData) {
												if (result.contains(str)) {// 有识别词
													ThreadPoolTaskAiui aiuiThread = new ThreadPoolTaskAiui("语义解析",postServer,result,SystemInfo.getMasterID(activity),"000000");
													poolManager.addAsyncTask(aiuiThread);
													break;
												}
											}
											mIsValidCmd = false;
											mSoundTip = false;
										}
									} else {
										// 是否提示打開交談模式
										if (ProjectUtils.getRootPath()
												.getInteractive() == 0) {
											if (!mSoundTip) {
												mSoundTip = true;
												playSound(5,"主人你可以打开交谈模式,要不你必須叫我的名字才能控制喔");
											}
										}
									}
								}
							}
						}
					} catch (Exception e) {
					}
					break;
				case AIUIConstant.EVENT_ERROR: {
					int errorCode = event.arg1;
					handleError(errorCode);
				}
					break;
				case AIUIConstant.EVENT_VAD: {
					if (AIUIConstant.VAD_BOS == event.arg1) {
						// showTip("找到vad_bos");
					} else if (AIUIConstant.VAD_EOS == event.arg1) {
						// showTip("找到vad_eos");
					} else {
						// mVolText.setText("" + event.arg2);
					}
				}
					break;
				default:
					break;
				}
			}
		};

		mSleepBroadCastRecerver = new SleepBroadCastRecerver();
		IntentFilter intentFilter = new IntentFilter(Constants.ACTION_SLEEP);
		registerReceiver(mSleepBroadCastRecerver, intentFilter);

		mResultHandler = new SemanticResultHandler(mContext);

		// 获得音量控制对象，并且音量设置为最大
		mVolumeManager =VolumeManager.getInstance();
		//mVolumeManager.setMaxVolume();
		mVolumeManager.setMidVolume();

		// 播放程序启动成功提示音
		mPlayController.playTone("", Constants.START_SUCCESS);
		mAIUIAgent = AIUIAgent.createAgent(activity, aiuiListener);
		try {
			AIUIMessage msg = new AIUIMessage(AIUIConstant.CMD_START, 0, 0, null,
					null);
			mAIUIAgent.sendMessage(msg);
		}catch (Exception e){

		}
	}

	// joe add 2017_1026
	public static void UploadText(String textString, int IsWakeLevel,int UploadMode) {
		if (null != mAIUIAgent) {
			// joe
			if(textString.length()>0){
				isUploadText = textString;
				isUploadIndex = 5;
				if (mIsWakeUp == 0) {
					mIsWakeUp = IsWakeLevel;
					AIUIMessage resetWakeupMsg = new AIUIMessage(
							AIUIConstant.CMD_WAKEUP, 0, 0, "", null);
					mAIUIAgent.sendMessage(resetWakeupMsg);
				}
				mWeatherMode = IsWakeLevel;
				musicIsSong = false;
				isAirbus = 0;
				//CheckMusic(textString);
				SendCMD cmdsend = SendCMD.getInstance();
				//cmdsend.sendCMD(0, textString, null);
				cmdsend.sendSubCmd(0, textString, null, UploadMode); //2
				String params = "data_type=text,debug=true";
				byte[] textData = textString.getBytes();
				AIUIMessage msg = new AIUIMessage(AIUIConstant.CMD_WRITE, 0, 0,
						params, textData);
				mAIUIAgent.sendMessage(msg);
				isLoad=true;
				startTime();
			}
		}
	}

	private void handleError(int errorCode) {
		boolean PlayMsgFlag = true;
		// AIUI为持续交互，错误码可能不断快速抛出，为保证只处理一次错误，这里先判断错误处理标记
		if (mIsHandlingError) {
			return;
		}

		// 按错误码设置不同的提示文本
		switch (errorCode) {
		case AIUIErrorCode.MSP_ERROR_TIME_OUT: // 服务器连接超时
		case AIUIErrorCode.ERROR_NO_NETWORK: // 无网络连接
		case AIUIErrorCode.MSP_ERROR_NO_RESPONSE_DATA: // 等待结果超时
		case AIUIErrorCode.MSP_ERROR_LMOD_RUNTIME_EXCEPTION: // 底层脚本出错
		case AIUIErrorCode.MSP_ERROR_NOT_FOUND: // aiui.cfg中scene参数设置出错
		case AIUIErrorCode.ERROR_SERVICE_BINDER_DIED: // 与AIUIService的绑定断开
		case AIUIErrorCode.MSP_ERROR_DB_INVALID_APPID: // appid校验不通过
		{
			mIsHandlingError = true;
			TonePlayer.stopPlay();
			String errorTip = "";
			if (AIUIErrorCode.MSP_ERROR_NOT_FOUND == errorCode) {
				errorTip = "场景参数设置出错！";
			} else if (AIUIErrorCode.ERROR_NO_NETWORK == errorCode) {
				errorTip = "网络未连接，请连接网络！";
			} else if (AIUIErrorCode.ERROR_SERVICE_BINDER_DIED == errorCode) {
				errorTip = "AIUI服务已断开！";
			} else if (AIUIErrorCode.MSP_ERROR_DB_INVALID_APPID == errorCode) {
				errorTip = "appid校验不通过!";
			} else {
				// 兜底提示文本
				// errorTip = "主人,我不明白您说的意思！";
				errorTip = "网络有点问题我去休息了，请稍后再试！";
				PlayMsgFlag = false;
			}
			if (PlayMsgFlag) {
				// 重置唤醒状态，当出现脚本错误时，需要重置AIUI服务
				playGoodByeTheSleep(
						errorTip,
						AIUIErrorCode.MSP_ERROR_LMOD_RUNTIME_EXCEPTION == errorCode);
			}
		}
			break;

		default:
			break;
		}
	}

	public void addAnHong(String str) {
		String result = ISocketCode.setPush(str, "000");
		sendCode(result);
	}

	public void playGoodByeTheSleep(String sleepText, final boolean resetAIUI) {
		// 若休眠文本不为空则合成文本，否则播放休眠提示音
		if (!TextUtils.isEmpty(sleepText)) {
			// 播放休眠文本
			if (null != mAIUIPlayer) {
				if (null != mAIUIPlayer) {
					mAIUIPlayer.stop();
				}
				PlayItem item = new PlayItem(ContentType.TEXT, sleepText,
						new Runnable() {

							@Override
							public void run() {
								mIsHandlingError = false;

								resetWakeup(resetAIUI);
							}
						});

				List<PlayItem> itemList = new ArrayList<PlayItem>();
				itemList.add(item);

				mAIUIPlayer.playItems(itemList, null);
			}
		} else {
			// 播放休眠提示音
			mPlayController.playTone("",
					Constants.XIAOAI_GOODBYE_NWZL, new Runnable() {
						@Override
						public void run() {
							resetWakeup(resetAIUI);
						}
					});
			MusicPlayMedia.getInstansMedia().setVol(true);
		}
		// mIsWakeUp = false;
	}

	public void resetAIUI() {
		if (null != mAIUIAgent) {
			// 发送reset消息，重置AIUI Service，相当于stop后再start
			AIUIMessage msg = new AIUIMessage(AIUIConstant.CMD_RESET, 0, 0,
					null, null);
			mAIUIAgent.sendMessage(msg);
		}
	}


	public void resetWakeup(boolean resetAIUI) {
		// 关闭指示灯
		DevBoardControlUtil.sleepLight();
		isTTS=false;
		// joe
		mIsWakeUp = 0;
		isUploadText = "";
		if (null != mAIUIAgent) {
			if (resetAIUI) {
				// 重置AIUI服务，当服务重置后将处于未唤醒状态
				AIUIMessage resetWakeupMsg = new AIUIMessage(
						AIUIConstant.CMD_RESET, 0, 0, "", null);
				mAIUIAgent.sendMessage(resetWakeupMsg);
			} else {
				// 重置唤醒状态
				AIUIMessage resetWakeupMsg = new AIUIMessage(
						AIUIConstant.CMD_RESET_WAKEUP, 0, 0, "", null);
				mAIUIAgent.sendMessage(resetWakeupMsg);
			}
		}
	}

	private class SleepBroadCastRecerver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// 接收到主动休眠广播重置唤醒，处理休眠
			// resetWakeup(false);
			playGoodByeTheSleep("", false);
		}
	}

	public String parseIatResult(String json) {
		StringBuffer ret = new StringBuffer();
		try {

			JSONObject tokener = new JSONObject(json);
			JSONObject object = tokener.getJSONObject("text");

			JSONArray words = object.getJSONArray("ws");
			for (int i = 0; i < words.length(); i++) {

				JSONArray items = words.getJSONObject(i).getJSONArray("cw");
				JSONObject obj = items.getJSONObject(0);
				ret.append(obj.getString("w"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ret.toString();
	}

	//public void startActivity() {
		// Intent intent = new Intent(activity, ReciveDataActivity.class);
		// startActivity(intent);
	//}

	public void setData(String balia) {
		Message msg = handler.obtainMessage();
		msg.what = 5;
		msg.obj = balia;
		handler.sendMessage(msg);
	}

	public void setSinglePlay(String param) {
		Message message = handler.obtainMessage();
		message.what = 11;
		message.obj = param;
		handler.sendMessage(message);
	}

	public void setCyclePlay() {
		handler.sendEmptyMessage(7);

	}

	public void setPrePlay() {
		handler.sendEmptyMessage(8);

	}

	public void setPause() {
		handler.sendEmptyMessage(9);

	}

	public void setSche() {
		handler.sendEmptyMessage(12);

	}

	public static void playSound(int Priority, String s) {
		if (!DoNotDisturb || (Priority >= 4)) {
			if ((Priority > prePriority) || (Priority == 5) || !isTTS) {
				if(musicTTsSt){
					if (MusicPlayMedia.getInstansMedia() != null) {
						MusicPlayMedia.getInstansMedia().pause();
					}
				}
				Log.e("play", s + " Priority:"+Priority +((isTTS)?" isTTS =true":" isTTS =false"));
				prePriority = Priority;
				if (null != mAIUIPlayer) {
					//mAIUIPlayer.stop();
					PlayItem item = new PlayItem(ContentType.TEXT, s, null);
					List<PlayItem> itemList = new ArrayList<PlayItem>();
					itemList.add(item);
					//isTTS = (!s.equals(""));
					mAIUIPlayer.playItems(itemList, new AIUIPlayerListener() {
						@Override
						public void onStop(PlayItem arg0) {
							Log.e("play", "stop isTTS = false");
							//HomeFragment.setCode("remenberNamePlay:" + "Stop");
                            isTTS = false;
						}
						@Override
						public void onStart(PlayItem arg0) {
							//AppTimeLogger.onTTSPlayStart(uuid);
							isTTS = true;
							Log.e("play", "start isTTS =true ");
							// HomeFragment.setCode("remenberNamePlay:" +
							// "Start");
						}
						@Override
						public void onResume(PlayItem arg0) {
							Log.e("play", "onResume isTTS = true");
                            //isTTS = true;
						}
						@Override
						public void onProgress(PlayItem arg0, int arg1) {
							//Log.e("play", "onProgress isTTS = false");
						}
						@Override
						public void onPause(PlayItem arg0) {
							Log.e("play", "onPause isTTS = false");
							//isTTS = false;
						}
						@Override
						public void onError(PlayItem playItem, int errorCode) {
							Log.e("play", "error isTTS = false");
							isTTS = false;
						}
						@Override
						public void onCompleted(PlayItem arg0, boolean arg1) {
							// AppTimeLogger.onTTSComplete(uuid);
							Log.e("play", "completed isTTS = false");
							mAIUIPlayer.stop(); //
							isTTS = false;
							if (MainActivity.activity.datas.size() > 0) {
								playSound(4,MainActivity.activity.datas.remove(0));
							}
						}
					});
				}
			} else {
				// Add Q
				MainActivity.activity.datas.add(s);
			}
		}
	}

	public static void playMusic(int songType,String s) {
		if (MusicPlayMedia.getInstansMedia() == null) {
			new MusicPlayMedia(mContext, "");
		}
		MusicPlayMedia.getInstansMedia().playURLList(null);
		//MusicPlayMedia.getInstansMedia().setFileName(1, s,true);
		MusicPlayMedia.getInstansMedia().setFileName(songType, s,0);
		try {
			MusicPlayMedia.getInstansMedia().play();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void getApkVersion(String toID, String param) {
		BasicInfo basicInfo=BasicInfoUtils.getBasic(activity);
		if(basicInfo!=null){
			String cmd = ISocketCode.setDownApk(
					"GreetingInfo:" +basicInfo.getGreetingInfo(),toID );
			sendCode(cmd);

			String cmd1 = ISocketCode.setDownApk(
					"WakeUp:" +basicInfo.getWakeUpWord(),toID );
			sendCode(cmd1);

		}
		new AsynDataJsonArrayTask(toID, param).execute();
	}

	public void downShow(String toID) {
		File file = new File(Environment.getExternalStorageDirectory(),
				Constants.appName);
		if (file.exists()) {
			file.delete();
		}
		DownAlert d = new DownAlert(activity, toID);
		d.show();
	}

	public void downServiceShow(String toID) {
		File file = new File(Environment.getExternalStorageDirectory(),
				Constants.appServiceName);
		if (file.exists()) {
			file.delete();
		}
		DownServiceAlert d = new DownServiceAlert(activity, toID);
		d.show();
	}

	private class AsynDataJsonArrayTask extends
			AsyncTask<String, Void, ResultInfo> {
		private String toID;
		private String param;

		public AsynDataJsonArrayTask(String _toID, String _params) {
			toID = _toID;
			param = _params.trim();
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}

		@Override
		protected ResultInfo doInBackground(String... params) {
			// TODO Auto-generated method stub
			ResultInfo result = null;
			try {
				if (param.equals("AIUIVersion")) {
					result = JSONHelper.parseObject(
							SettingServiceUtils.getVersion("SetAIUIVersionV2"),
							ResultInfo.class);
				} else {
					result = JSONHelper.parseObject(
							SettingServiceUtils.getVersion("SetVersionV2"),
							ResultInfo.class);
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return result;
		}

		@Override
		protected void onPostExecute(ResultInfo result) {
			// TODO Auto-generated method stub
			// super.onPostExecute(resString);
			if (result != null && result.getResultCode() == 1) {
				try {
					if (param.equals("AIUIVersion")) {
						String apkCode = result.getMsg().trim();
						String current = getVersion().trim();
						String city=ProjectUtils.getRootPath().getCity();
						if (apkCode.equals(current)) {
							String cmd = ISocketCode.setDownApk("ApkNew:当前版本"
									+ current+"city:"+city, toID);
							sendCode(cmd);
						} else {
							String cmd = ISocketCode.setDownApk(
									"ApkUpdate:当前版本" + current+"city:"+city, toID);
							sendCode(cmd);
						}

					} else {
						int apkCode = Integer.parseInt(result.getMsg());
						int current = CurrentVersion.getVerCode(mContext);
						String versionName = CurrentVersion
								.getVerName(mContext);
						int vol=MusicPlayMedia.getVolume();
						if (current < apkCode) {
							String cmd = ISocketCode.setDownApk(
									"ApkUpdate:叮咚当前版本" + versionName+"vol:"+vol, toID);
							sendCode(cmd);
						} else {
							String cmd = ISocketCode.setDownApk("ApkNew:叮咚最新版本"
									+ versionName+"vol:"+vol, toID);
							sendCode(cmd);
						}
					}
				} catch (NameNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else {
				if (param.equals("AIUIVersionV2")) {
					String cmd = ISocketCode.setDownApk("ApkNew:当前版本"
							+ getVersion().trim(), toID);
					sendCode(cmd);

				} else {
					int vol=MusicPlayMedia.getVolume();
					String cmd = ISocketCode.setDownApk("ApkNew:叮咚最新版本"
							+ CurrentVersion.getVerName(mContext)+"vol:"+vol, toID);
					sendCode(cmd);
				}
			}
		}
	}

	public void serialReceive(String s) {
		// TODO Auto-generated method stub
		Log.e("DomTao","R_"+s);
		Message msg = handler.obtainMessage();
		msg.what = 6;
		msg.obj = s;
		handler.sendMessage(msg);
	}

	private void buildGrammar() {
		String grammar = FileUtil.readAssetsFile(mContext, GRAMMAR_FILE_PATH);
		AIUIMessage buildGrammar = new AIUIMessage(
				AIUIConstant.CMD_BUILD_GRAMMAR, 0, 0, grammar, null);
		mAIUIAgent.sendMessage(buildGrammar);
		// Log.d(TAG,"sendMessage start");

	}

	public String getVersion() {
		String result = "0.0.0";
		if (null != mAIUIAgent) {
			// 获取AIUI Service的版本号
			result = mAIUIAgent.getServiceVersion();
		}
		return result;
	}

	private static boolean isLoad = true;

	private static void startTime() {

		new Thread(new Runnable() {
			@Override
			public void run() {
				while (isLoad) {
					try {
						Thread.sleep(1000);
						if (isUploadIndex > 0) {
							isUploadIndex--;
							if (isUploadIndex <= 0) {
								isUploadText = "";
								if (mIsWakeUp < 255) {
									activity.resetWakeup(false);
								}
							}
						} else {
							isLoad = false;
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}

	/**
	 * 执行shell指令
	 *
	 * @param cmd
	 *            指令
	 */
	public final void exec(String cmd) {
		try
		{
			if(!inputKey){
				inputKey=true;
				runtime = Runtime.getRuntime();
				Process proc=runtime.exec("su");
			}
			//OutputStream su = Runtime.getRuntime().exec("su").getOutputStream();
			//需要重复执行仅重新执行以下代码即可，否则速度回非常慢
			Process proc = runtime.exec(cmd);
			Log.e("text","exec "+cmd);
		}
		catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.e("text","exec "+ e.getMessage());
		}
	}

}